import React, { useCallback, useEffect } from 'react';
import { InfiniteScroll, PullToRefresh } from "antd-mobile";
import * as styles from '../styles/view.scss';
import Base from './base';

const renderNoData = (noDataTip, property, renderHeader, renderRow) => {
  return <div className={styles.divNoData}>
    {property.isHasHeader && renderHeader()}
    {property.isHasNoDataRow
      ? renderRow({ isNoData: true })
      : <div className={styles.divNoDataTip}>
        <span style={property.noDataStyle}>{noDataTip}</span>
      </div>}
  </div>;
};

const loadData = (property, pageIndexChange, pageIndex) => {
  if (property.setLoadComplete) return;

  return new Promise((resolve) => {
    pageIndexChange(pageIndex);

    property.setLoadComplete = () => {
      resolve();
      property.setLoadComplete = null;
    };
  });
};

export default React.memo((props) => {
  const { property, renderHeader, dataList, pageIndexChange, pageIndex, hasMore, renderRow } = props;

  const onRefresh = useCallback(() => loadData(property, pageIndexChange, 1), [property, pageIndexChange]);

  const loadMore = useCallback(() => loadData(property, pageIndexChange, pageIndex + 1), [property, pageIndexChange, pageIndex]);

  useEffect(() => {
    if (property.setLoadComplete) property.setLoadComplete();
  }, [dataList, property]);

  if (!dataList) return null;

  if (dataList.length === 0) return renderNoData(property.noDataTip || '暂无数据', property, renderHeader, renderRow);

  let hasData = dataList.length > 0;
  if (hasData && dataList.length === 1 && dataList[0].isNoData) hasData = false;

  const className = styles[property.listClassName || 'divData'];
  const className2 = styles[property.listClassName2 || 'divData2'];

  return (<React.Fragment>
    <PullToRefresh onRefresh={onRefresh}>
      <div className={className2} style={Base.setStyle(property.listViewStyle2)}>
        <div className={className} style={Base.setStyle(property.listViewStyle)}>
          {renderHeader()}
          <div style={Base.setStyle(property.itemsStyle)} className='divRows'>{dataList.map((m, i) => renderRow(m, i))}</div>
        </div>
      </div>
    </PullToRefresh>
    {hasData && <InfiniteScroll loadMore={loadMore} hasMore={hasMore} threshold={50} />}
  </React.Fragment>);
});